package com.example.SpringDataJDBC;

import com.example.SpringDataJDBC.entity.MyRowMapper;
import com.example.SpringDataJDBC.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public class UserRepository {

  private final JdbcTemplate jdbcTemplate;

  @Autowired
  public UserRepository(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  public List<User> findAll() {
    List<User> userList = jdbcTemplate.query("select * from user", new Object[]{}, new BeanPropertyRowMapper<User>(User.class));
    return userList;
  }
  public Optional<User> findByName(String name) {
    String sql = "SELECT * FROM user WHERE name=?";
    User user = jdbcTemplate.queryForObject(sql, new MyRowMapper(),name);
    return Optional.of(user);
  }
  public Optional<User> findById(Long id) {

      return Optional.ofNullable(jdbcTemplate.queryForObject("select * from user where id =  ?"
          , new Object[]{id}
          , (rs, i) -> new User(rs.getLong("id"), rs.getString("name"), rs.getInt("age"),rs.getString("gender"))));
  }
  public User update(User user) {
    String sql = "update user set "
            +"name=?,"
            +"age=?,"
            +"gender=? where id=?";
     jdbcTemplate.update(sql,
            user.getId(),
            user.getName(),
            user.getAge(),
             user.getGender());

    return user;
  }

  public void deleteById(Long id) {
    jdbcTemplate.update("delete from user where id =  ?", id);
  }


}
